package com.chen.back.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.back.entity.Permission;
import com.chen.back.entity.Role;
import com.chen.back.entity.RolePermission;
import com.chen.back.mapper.RoleMapper;
import com.chen.back.response.Result;
import com.chen.back.service.PermissionService;
import com.chen.back.service.RolePermissionService;
import com.chen.back.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chen
 * @since 2022-02-24
 */
@RestController
@RequestMapping("/permission")
public class PermissionController extends BaseController{
@Autowired
private PermissionService permissionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionService rolePermissionService;
//获取当前的权限菜单
@GetMapping("/menu")
@RequiresPermissions("permission:menu")
public String  list() {

    List<Permission> menus = permissionService.tree();
//    List<Permission> list = permissionService.list();
    return JSON.toJSONString(new Result().setCode(200).setData(menus));

}

    @GetMapping("/set")
    @RequiresPermissions("permission:set")
    public String list(String roleName) {



        Page<Role> pageData = roleService.page(getPage(),
                new QueryWrapper<Role>()
                        .like(StrUtil.isNotBlank(roleName), "role_name", roleName)
        );
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(roleName), "role_name", roleName);

        Integer total = roleMapper.selectCount(wrapper);
        pageData.setTotal(total);
        return JSON.toJSONString(new Result().setCode(200).setData(pageData));

    }

    @PostMapping("/perm/{roleId}")
    public String  info(@PathVariable("roleId") Integer roleId, @RequestBody Integer[] permissionIds) {
        System.out.println("是否进行");
        List<RolePermission> rolePermissions = new ArrayList<>();

        Arrays.stream(permissionIds).forEach(permissionId -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(permissionId);
            rolePermission.setRoleId(roleId);

            rolePermissions.add(rolePermission);
        });

        // 先删除原来的记录，再保存新的
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        rolePermissionService.saveBatch(rolePermissions);

        // 删除缓存


        return JSON.toJSONString(new Result().setCode(200).setData(permissionIds));

    }

    @PostMapping("/save")
    public String save(@RequestBody Permission permission) {


        permissionService.save(permission);
        return JSON.toJSONString(new Result().setCode(200).setData(permission));

    }

    @PostMapping("/update")
    public String update( @RequestBody Permission permission) {


        permissionService.updateById(permission);

        // 清除所有与该菜单相关的权限缓存
        return JSON.toJSONString(new Result().setCode(200).setData(permission));

    }

    //前端是/info/id是没有关系的，这里id与prmissionId形参一样的，然后将prmission的值传入到ermission
    @GetMapping("/info/{prmissionId}")
    public String info(@PathVariable(name = "prmissionId") Integer ermissionId) {
        return JSON.toJSONString(new Result().setCode(200).setData(permissionService.getById(ermissionId)));

    }

    @PostMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {

        int count = permissionService.count(new QueryWrapper<Permission>().eq("father_id", id));
        if (count > 0) {
            return JSON.toJSONString(new Result().setCode(200).setData("请删除子菜单"));

        }



        permissionService.removeById(id);

        // 同步删除中间关联表
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("permission_id", id));
        return JSON.toJSONString(new Result().setCode(200).setData("删除成功"));

    }

}
